//
//  ZpUserAccountViewModel.m
//  WeiBo_OC
//
//  Created by MacBook Pro on 16/5/28.
//  Copyright © 2016年 MacBook Pro. All rights reserved.
//

#import "ZpUserAccountViewModel.h"
#import "ZpNetWorkTool.h"
#import "ZpNetWorkInfo.h"
#import "ZpUserAccount.h"
@interface ZpUserAccountViewModel()

@property (nonatomic, strong) ZpNetWorkTool *tool;
@end
@implementation ZpUserAccountViewModel

+ (instancetype)shareUserAccountViewModel
{
    static ZpUserAccountViewModel *viewModel;
    static dispatch_once_t one;
    dispatch_once(&one, ^{
        viewModel = [[ZpUserAccountViewModel alloc] init];
    });

    
    return viewModel;
}

- (instancetype)init{
    if (self = [super init]) {
        self.tool = [ZpNetWorkTool shareNetWorkTool];
        self.userAccount = [self loadUserAccount];
    }
    return self;
}

//- (void)setUserAccount:(NSDictionary *)dict{
//    if (dict) {
//        _userAccount = [ZpUserAccount userAccount:dict];
//    }
//    _userAccount = [ZpUserAccount userAccount:dict];
//}

- (NSURLRequest *)loadWebView{

    NSString *urlString = [NSString stringWithFormat:@"%@%@client_id=%@&redirect_uri=%@", self.tool.info.host, self.tool.info.respource_oauth,self.tool.info.client_id, self.tool.info.redirect_uri];
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    return request;
}


- (void)loadUserAccountWithCode:(NSString *)code andFinshed:(void(^)(NSError *error))finshed{

    NSDictionary *parameters = @{
                                 @"client_id" : self.tool.info.client_id,
                                 @"client_secret": self.tool.info.client_secret,
                                 @"grant_type": self.tool.info.grant_type,
                                 @"code":code,
                                 @"redirect_uri":self.tool.info.redirect_uri};
    
    __block NSDictionary *tokenDict;
    
    NSString *urlString = [NSString stringWithFormat:@"%@%@", self.tool.info.host, self.tool.info.resource_token];

    [[ZpNetWorkTool shareNetWorkTool] sendHttpRequestWithMethod:POST andParameters:parameters andURLString:urlString andfinshed:^(NSData *data, NSError *error) {
        
        tokenDict = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSString *urlString = [NSString stringWithFormat:@"%@%@", self.tool.info.host, self.tool.info.resource_userInfo];

        NSDictionary *dicts = @{
                                @"access_token" : tokenDict[@"access_token"],
                                @"uid" : tokenDict[@"uid"]
                                };
        
        [[ZpNetWorkTool shareNetWorkTool] sendHttpRequestWithMethod:GET andParameters:dicts andURLString:urlString andfinshed:^(NSData *data, NSError *error) {
            NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            NSLog(@"%@", dict);
            ZpUserAccount *userAccount = [ZpUserAccount shareUserAccount];
            [userAccount setValueForDict:dict];
            userAccount.access_token = tokenDict[@"access_token"];
            userAccount.uid = tokenDict[@"uid"];
            userAccount.expires_in = [tokenDict[@"expires_in"] doubleValue];
            self.userAccount = userAccount;
            [self saveUserAccount];
            finshed(error);
        }];
        
    }];
    

}




- (NSString *)needToSendHttpRequest:(NSURLRequest *)request
{
    NSString *urlString = request.URL.absoluteString;
    NSString *successFlag = @"code=";
    if ([urlString containsString:successFlag]) {
        //截取字符串中的某个字符串
        NSRange range = [urlString rangeOfString:successFlag];
        NSString *code = [urlString substringFromIndex:range.location + range.length];
        NSLog(@"%@", urlString);
        NSLog(@"%@", code);
        
        return code;
    }
    return nil;
}

#pragma -mark 读取和保存偏好设置
- (void)saveUserAccount{
    NSArray *keys = @[@"access_token",@"expires_in",@"uid",@"name",@"avatar_large", @"expires_date"];
    NSDictionary *userInfo = [self.userAccount dictionaryWithValuesForKeys:keys];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setObject:userInfo forKey:@"userAccount"];
    [userDefault synchronize];
    
}

- (ZpUserAccount *)loadUserAccount{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSDictionary *dict = [userDefault objectForKey:@"userAccount"];
    if (dict) {
        ZpUserAccount *userAccount = [ZpUserAccount shareUserAccount];
        [userAccount setValueForDict:dict];
        return userAccount;
    }else{
        return nil;
    }
    
}
@end
